<?php

namespace app\store\controller;
use think\Request;
use think\Session;
use think\Db;
class Payment extends ApiCommon {
    
    public $payment; //  具体的支付类
 	public $pay_code;
	

    /**
     * 析构流函数
     */
    public function  __construct() {                
		$this->pay_code = 'miniAppPay';     
		include_once  "plugins/payment/weixin/weixin.class.php";
        $code = '\\weixin';
        $this->payment = new $code();
    }
   
    public function testpayimport(){
    	$buyres = db('buylist')->where(['order_sn'=>'2owfcmonwg'])->select();
    	$isok = update_import_payback($buyres);
		$this->returnMsg('ok',$isok);
    }
    
    /**
     *  提交支付方式
     */
    public function pay_code(){                        
        $goodsid = input('goodsid/d',0); // 商品id
        $userid = input('uid/d',0); // userid
        $num = input('num/d',0); // 数量
        
		$userinfo  = db('userinfo')->where(['userid'=>$userid])->field('openid,unionid,role,storeid')->select();
		if(count($userinfo)<=0){
			$this->returnMsg('-1','用户信息错误');
		}
		
		$userinfo_p  = db('userinfo_p')->where(['unionid'=>$userinfo[0]['unionid']])->field('unionid,phone')->select();
		if(count($userinfo_p)<=0){
			$this->returnMsg('-1','用户信息错误..');
		}
		                   
		$result = db('goods')->where(['id'=>$goodsid])->select();
		if(empty($result) || count($result)<=0){
			$this->returnMsg('-1','商品信息错误');
		}
		
		$price = $result[0]['price']*100 *$num;
		$goodsBuytype = $result[0]['buyType'];
		$gname = $result[0]['gname'];
		$phone = $userinfo_p[0]['phone'];
		$role = $userinfo[0]['role'];
		$storeid = $userinfo[0]['storeid'];
		$goodstype = $result[0]['type'];
		
		$bossid = config('Boss');
		
		
		
		if($phone == null || $phone == ''){
			$this->returnMsg('-2','请先绑定手机号码');
		}
		
		if($price<=0){
			$this->returnMsg('-8','不出售没有价格的商品');
		}
		
		$bresult = db("buylist")->where(['userid'=>$userid,'goodsid'=>$goodsid,'paystate'=>1])->select();
		if(count($bresult)>0 && $goodsBuytype == 1){
			$this->returnMsg('-3','该商品只能购买一次');
		}
		
		$bossinfo = Db::query("select userid from ml_userinfo where role = 2 and storeid = $storeid");
		if(count($bossinfo)<=0){
			$this->returnMsg('-4','店铺还没有绑定商户');
		}
		
		//项目引进
		if($goodstype == 5){
			if($role!=$bossid){				
				$this->returnMsg('-9','亲.项目引进只能够商户购买哦');
			}
			
			if($num>1){
				$this->returnMsg('-10','亲.项目引进只能购买一件哦');
			}
		}
		
		//推荐人编码
		//db('userinfo')->where(['userid'=>$userid])->save(['tid'=>$extid]);		
//		$attach = 'GoodsPayParam'.';'.$userid.';'.$gname.';'.$price.';'.$goodsid.';'.$num;
		
		//tpshop 订单支付提交
        $config_value['body'] = $gname;
		$config_value['openid'] = session('openid');//$userinfo[0]['openid'];
		
		$order = [];
		$order['order_sn'] = get_rand_str(10,0,1);
		$order['price'] = $price;
		$order['goodsid'] = $goodsid;
		$order['userid'] = $userid;
		$order['setsname'] = $gname;
		$order['buydate'] = time();
		$order['orderstate'] = 0;
		$order['buyNum'] = $num;
		$order['paystate'] = 0;
		$order['storeid'] = $userinfo[0]['storeid'];
		
		$orderid = db('buylist')->add($order);
		$order['oid'] = $orderid;

		//小程序支付
        $code_str = $this->payment->get_code($order,$config_value);	
		if(isset($code_str['return_code'])){
			$return_code = $code_str['return_code'];
			if($return_code == "FAIL"){
				 $this->returnMsg('-1',$code_str['return_msg']);
			}
		}
		
		
	    $this->returnMsg('ok','',$code_str);
    }

    // 服务器返回方法
    public function notifyUrl(){            
        $this->payment->response(); 
		$this->returnMsg('ok','back..');
        exit();
    }
	
	//提现
	public function withdraw_handle(){
		
		//exit(ceil(floatval(0.5*100*0.006)));
		
		$userid = input('uid/d',0);
		$money =  input('money');//input('money/d',0);
		$pwd = input('pwd/d',0);
		
		$minmoney = 0.5;
		$money = floatval($money);
		if($money<$minmoney){
			$this->returnMsg('-1','提现金额必须大于'.$minmoney.'元');
		}
		
		$userresult = Db::query("select accounts,extrapwd,openid,storeid,unionid from ml_userinfo where userid = $userid");
		if($userresult==null||count($userresult)<=0){
			$this->returnMsg('-1','用户信息不存在');
		}
		
		$userinfo_p  = db('userinfo_p')->where(['unionid'=>$userresult[0]['unionid']])->field('unionid,phone,username')->select();
		if(count($userinfo_p)<=0){
			$this->returnMsg('-1','用户信息错误..');
		}
		
		if(empty($userinfo_p[0]["phone"])){
			$this->returnMsg('-2','请先绑定手机号码');
		}
		
		
		$storeid = $userresult[0]['storeid'];
		$account = $userresult[0]['accounts'];
		if($userresult[0]['accounts'] < $money){
			$this->returnMsg('-4','余额不足');
		}		
		else{
			$time = time();
			$sum = $account-$money;
			
			$logintp = session('logintp');
			$appid = '';
			if($logintp == 'h5'){
				$appid = config('WxAppId');
			}
			else{
				$storeid = session('storeid');
				$storeinfo  = Db::name('store')->where(['store_id'=>$storeid])->select();
				if(count($storeinfo)<=0){
					$this->returnMsg('-7','店铺信息错误');
				}
				$appid = $storeinfo[0]['appid'];
			}
			
			$openid = session('openid');
			$moneyval = (-1)*$money;
			$username = $userinfo_p[0]['username'];
			$deletenum = ceil(floatval($money*100*0.01));
			//$deletenum = $deletenum<10?10:$deletenum;
			$getmoney = $money*100 - $deletenum;
			
			$drawid = db('withdrawlist')->add(['userid'=>$userid,'drawdate'=>$time,'sum'=>$money,'storeid'=>$storeid,'openid'=>$openid,'appid'=>$appid]);
			
			$tdata=array(
				'openid'=>$openid,//openid
				'check_name'=>'NO_CHECK',//是否验证真实姓名参数
				're_user_name'=>$username,//姓名
				'amount'=>$getmoney,//最小1元 也就是100
				'desc'=>config('ComPanyName')."提现通知"//描述
			);
			
			$drawstate =  $this->payment->transfer($tdata,$appid);
			if($drawstate == "SUCCESS"){
				db('withdrawlist')->delete(['drawid'=>$drawid]);
				db('userinfo')->where(['userid'=>$userid])->save(['accounts'=>$sum]);
				db('userconsume')->add(['usetype'=>3,'userid'=>$userid,'nums'=>$moneyval,'opdate'=>time(),'storeid'=>$storeid,'clientname'=>$username,'remark'=>'微信提现']);				
				$this->returnMsg('ok','提现成功',$sum);
			}
			else if($drawstate == 'NOTENOUGH'){
				//余额不足。请稍等后台审核
				$this->returnMsg('ok','提现金额将在24小时到您账户。',$account);
			}
			else if($drawstate == 'SENDNUM_LIMIT'){
				$this->returnMsg('-7','到达今日提现次数上限！');
			}
			else{
				$this->returnMsg('-6','提现失败'.$drawstate);
			}		
		}
	}		

	
}
